package com.ssmintegration.controller;

import com.google.gson.Gson;
import com.ssmintegration.entity.User;
import com.ssmintegration.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping(value = "/user",produces = "text/html;charset=utf-8")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public String login(User user){
        System.out.println(user);
        if (userService.login(user) == null) {
            return "error";
        }
        return "user";
    }

    @ResponseBody
    @RequestMapping("/findUserByUsername")
    public String findUserByUsername(String condition){
        List<User> users = userService.findUser(condition);
        System.out.println(users.get(0));
        Gson gson = new Gson();
        return gson.toJson(users);
    }

    @ResponseBody
    @RequestMapping(value = "/register")
    public String register(User user){
        int count = userService.register(user);
        String msg = "";
        if(count == 1){
            msg = "注册成功";
        }else if(count == 0){
            msg = "注册失败";
        }else if(count == 2){
            msg = "用户名存在";
        }else{
            msg = "内部错误";
        }
        Gson gson = new Gson();
        return gson.toJson(msg);
    }

    @ResponseBody
    @RequestMapping("/updateUser")
    public String updateUser(User user){
        String msg = "";
        if(userService.updateUser(user) == 1){
            msg = "修改成功";
        }else{
            msg = "修改失败";
        }
        return msg;
    }

    @ResponseBody
    @RequestMapping("/deleteUser")
    public String deleteUser(String username){
        String msg = "";
        if(userService.deleteUser(username) == 1){
            msg = "删除成功";
        }else{
            msg = "删除失败";
        }
        return msg;
    }

//    @ResponseBody
//    @RequestMapping("/testSearch")
//    public String testSearch(String user1, String user2, String user3){
//        List<String> usernames = new ArrayList<>();
//        usernames.add(user1);
//        usernames.add(user2);
//        usernames.add(user3);
//        List<User> users = userService.testSearch(usernames);
//        Gson gson = new Gson();
//        return gson.toJson(users);
//    }

}
